package com.nti56.springboot.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nti56.springboot.cache.BaseDataCache;
import com.nti56.springboot.exception.MyRuntimeException;
import com.nti56.springboot.mapper.tmsmapper.DictMapper;
import com.nti56.springboot.model.Dict;
import com.nti56.springboot.model.DictItem;
import com.nti56.springboot.utils.ParamUtil;

@Service
public class DictService {
	
	private static final Logger logger = LoggerFactory.getLogger(DictService.class);
	
	@Autowired
    private DictMapper dictMapper;
	
	@Resource
	DictItemService dictItemService;
	
	@Autowired
	private BaseDataCache baseDataCache;
	
	public void refreshCache() {
		List<Dict> dictList = this.findAll(null);		
		baseDataCache.putDicts(dictList);
	}
	
	public Dict getById(String id) {
		return dictMapper.getById(id);
	}
	
	public List<Dict> findAll(Map params){
		return dictMapper.findAll(params);
	}
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void insert(Dict dict,List<DictItem> items) {
		Long cnt = dictMapper.countByMap(ParamUtil.setParam("dictCode", dict.getDictCode()));
		if(cnt > 0) {
			logger.error("字典编码:"+dict.getDictCode()+" 已经存在请勿重复添加!");
			throw new MyRuntimeException("字典编码:"+dict.getDictCode()+" 已经存在请勿重复添加!");
		}
		dictMapper.insert(dict);
		for(DictItem dictItem : items) {
			dictItem.setDictId(dict.getDictId());
			dictItemService.insert(dictItem);
		}
	}
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void update(Dict dict,List<DictItem> items) {
		Map map = ParamUtil.setParam("dictCode", dict.getDictCode())
				.setParam("dictIdNotEq", dict.getDictId());
		Long cnt = dictMapper.countByMap(map);
		if(cnt > 0) {
			logger.error("字典编码:"+dict.getDictCode()+" 已经存在请勿重复修改!");
			throw new MyRuntimeException("字典编码:"+dict.getDictCode()+" 已经存在请勿重复修改!");
		}
		dictItemService.deleteByDictId(dict.getDictId());
		dictMapper.update(dict);
		for(DictItem dictItem : items) {
			dictItem.setDictId(dict.getDictId());
			dictItemService.insert(dictItem);
		}
	}
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void delete(String dictId) {
		dictMapper.delete(dictId);
	}
	
	
	@Transactional(rollbackFor = Exception.class, transactionManager = "tmsTransactionManager")
	public void deleteBatch(List<String> list) {
		dictMapper.deleteBatch(list);
	}
}
